#include "widget.h"
#include "ui_widget.h"

#include <QMessageBox>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 0.设置窗口标题
    this->setWindowTitle("服务端");

    // 1.创建socket对象
    udpSocket = new QUdpSocket(this);

    // 2.连接信号和槽
    connect(udpSocket, &QUdpSocket::readyRead, this, &Widget::processRequest);
//    connect(ui->pushButton, &QPushButton::clicked, this, &Widget::processRequest);

    // 3.绑定端口
    bool ret = udpSocket->bind(QHostAddress::Any, 9090);
    if(!ret)
    {
        QMessageBox::critical(this, "服务器启动出错", udpSocket->errorString());
        exit(1);
    }
}

Widget::~Widget()
{
    delete ui;
}

void Widget::processRequest()
{
    // 1.获取客户端发送过来的报文
    const QNetworkDatagram& requestDatagram = udpSocket->receiveDatagram();
    // 2.获取请求正文
    QString request = requestDatagram.data();
    // 3.构建响应正文
    QString response = process(request);
    // 4.构建响应报文并发送
    QNetworkDatagram responseDatagram(response.toUtf8(), requestDatagram.senderAddress(),requestDatagram.senderPort());
    udpSocket->writeDatagram(responseDatagram);
    // 5.把这次交互的信息显示到界面上
    QString log = "["+requestDatagram.senderAddress().toString()+":"+QString::number(requestDatagram.senderPort())+"]"+"请求："+request;
    ui->listWidget->addItem(log);
}

QString Widget::process(QString request)
{
    return request;
}



























